/**
 * Created by joustany on 17/11/21.
 */
/**
 * 两数相减
 * */
ajaxStart()
ajaxComplete()
function accSub(arg1, arg2) {
    return parseFloat((parseInt(arg1 * 1000) - parseInt(arg2 * 1000)) / 1000)
}
/**
 * 两数相加
 * @param arg1
 * @param arg2
 * @return {Number}
 */
function accAdd(arg1, arg2) {
    // console.log(arg1, arg2, arg1 * 100 + arg2 * 100, (arg1 * 100 + arg2 * 100) / 100)
    return parseFloat((parseInt(arg1 * 1000) + parseInt(arg2 * 1000)) / 1000)
}
/**
 * 两数相乘
 * @param arg1
 * @param arg2
 * @return {Number}
 */
function accMul(arg1, arg2) {
    return parseFloat((parseInt(arg1 * 1000) * parseInt(arg2 * 1000)) / 1000000)
}
var total = 0
var count //判断用户是否有红包
var params = window.localStorage
var num //红包数量
var id //红包id
var no //红包状态
var payment //支付枚举
var param = JSON.parse(params.user)//参数
var platform = param.platform
var web = ''

$(function () {
    // var params = window.localStorage
    getShopView()
})
//显示请求数据
function getShopView() {
    console.log(param)
    // var params = JSON.parse(param.user)
    // var redirect = JSON.parse(decodeURIComponent(param['redirect']));
    var items = JSON.parse(window.localStorage.items) //通过本地传递数据
    var redirect = JSON.parse(decodeURIComponent(param['redirect']));
    // var items = JSON.parse(items)
    $.ajax({
        url: configApi('/user-account/view'),
        data: {
            access_token: redirect.token,
        },
        dataType: 'json',
        type: "POST",
    }).done(function (res) {
        "use strict"
        if (res.success) {
            console.log(res.data.balance)
            foodView(items, res.data.balance)
        } else {
            layer.open({
                content: res.message
                , skin: 'msg'
                , time: 2 //2秒后自动关闭
            });
        }
    })
}
//显示页面
function foodView(foods,balance) {
    "use strict"
    console.log(foods)
    var sum = balance
    // var params = JSON.parse(packet.user)
    // var platform= params.platform
    // platform = 'alipay'
    if (platform === 'wechat') {
        platform = 'wechat'
    }else {
        $('.platform-wechat .platform_logo img').attr('src','./images/ui_icon/支付宝.png')
        $('.platform-wechat span').text('支付宝支付')
    }
    total = foods.total
    console.log(foods.balance)
    if (sum < total){
        // $('.balance-content').find('.icon img').attr('src','./images/ui_icon/Oval.png')
        $('.platform-wechat').find('.icon img').attr('src','./images/ui_icon/选择.png')
        $('.balance-content').removeAttr('onclick');
        $('.balance-content').find('.icon').html('余额不足')
        $('.balance-content').find('.icon').addClass('font—icon')
    }else {
        $('.balance-content').find('.icon img').attr('src','./images/ui_icon/选择.png')
        $('.balance-content').attr('data-pay','1')
    }
    console.log(platform)
    var html = ''
    var discount = foods.discounts[0]
        count = foods.coupon_count
    $.each(foods.items,function(index,item){
        console.log(item.img)
        html +='<div class="food">'
        html +='<div class="name"><img src="'+ item.img+'" alt="">'+ item.name +'</div>'
        html +='<div class="count"><span>x&nbsp<span class="num">' + item.num + '</span></span><div class="food_price"><span class="rmb">¥</span><span class="price">' +item.promotion_price+ '</span></div></div>'
        html +='</div>'
    })
    $('.food-container').html(html);
    $('.packet_total .total').html(foods.total)
    $('.all-price').html(foods.total)
    $('.surplus-content .surplus-at .price').text(sum)
    $('.surplus-content .surplus-deduct .price').text(foods.total)
    $('.balance-content .num').text(sum)
    console.log(params)
    if(foods.discounts.length == 0){
        $('.discounts').hide()
        if(count == 0){
            $('.cart-count').text('')
        }
    }else {
        $('.amount').text(discount.amount)
        $('.cart-count .count').text(discount.amount)
    }
    //选择红包状态判断本地是否有红包
    var packet = $.urlGet()
    no = packet.no
    console.log(packet.no)
    if (count == 0){
        $('.packet_count .count').html('暂无可用红包')
        $('.packet_count .count').addClass('count_wu')
        // $('.cart-count').text('')
    } else if(packet.no == '2'){
        num = packet.num
        id = packet.id
        $('.packet_count .count .num').text(packet.num)
        //如果有优惠商品优惠价加红包
        $('.cart-count .count').text(packet.num)
        if (foods.discounts.length == 0){
            $('.cart-count .count').text(packet.num)
        }else {
            $('.cart-count .count').text(accAdd(packet.num, discount.amount))
        }
        $('.all-price').html(accSub(foods.total,packet.num))
        $('.surplus-content .surplus-deduct .price').text(accSub(foods.total,packet.num))
        $('.packet_total .total').html(accSub(foods.total,packet.num))
    }else {
        if (count == '0'){
            $('.cart-count').text('')
        }
        if(foods.discounts.length == 0){
            $('.cart-count').text('')
        }
        $('.packet_count .count').html(foods.coupon_count + '可用红包')
        $('.packet_red .count').addClass('packet_with')
        $('.packet_count .count').addClass('with')
    }
    //账户余额
}
//点击选择红包
$(document).on('click','.packet_red',function () {
    console.log(params)
    if(!count == 0){
        params.price = total
        window.location.href = './chooseWelfare.html?num='+ num +'&id='+ id +'&no='+ no +''
    }
})
function balanceHandle(that) {
    console.log($(that))
    $(that).find('.icon img').attr('src','./images/ui_icon/选择.png')
    $(that).attr('data-pay','1')
    $('.platform-wechat').removeAttr("data-pay");
    $('.platform-wechat').find('.icon img').attr('src','./images/ui_icon/Oval.png')
}
$(document).on('click','.platform-wechat',function () {
    console.log('aaa')
    $(this).find('.icon img').attr('src','./images/ui_icon/选择.png')
    $('.balance-content').find('.icon img').attr('src','./images/ui_icon/Oval.png')
    $(this).attr('data-pay','2')
    $('.balance-content').removeAttr("data-pay");
})
//点击支付
$(document).on('click','.surplus-content .title .icon',function () {
    "use strict"
    behavior.track("取消支付",{
        "platform":"余额"
    })
    $('.surplus-container').hide()
})
$(document).on('click','.surplus-pay',function () {
    "use strict"
    $('.surplus-container').hide()
    payment = '3'
    order(param,payment)
})
$(document).on('click','.submit-btn-red',function () {
    // console.log($('.balance-content').attr('data-pay'))
    // console.log(redirect)
    // console.log(param)
    var redirect = JSON.parse(decodeURIComponent(param['redirect']));
    $.ajax({
        url: configApi('/user-account/view'),
        data: {
            access_token:redirect.token,
        },
        dataType: 'json',
        type: "POST",
    }).done(function (res) {
        "use strict"
        if (res.success){
            // console.log(res.data.balance)
            $('.balance-content .platform_logo .num').text(res.data.balance)
            $('.surplus-content .surplus-at .price').text(res.data.balance)
            if ($('.balance-content').attr('data-pay') === '1'){
                //余额支付
                $('.surplus-container').show()
            }else {
                //微信支付
                // console.log('bbbb')
                // console.log(platform)
                if(platform == 'wechat'){
                    payment = '1'
                }else{
                    payment = '2'
                }
                order(param,payment)
            }
        }else {
            layer.open({
                content: res.message
                ,skin: 'msg'
                ,time: 2 //2秒后自动关闭
            });
        }
    })
    //删除红包标记
})
//调起支付
var jsApiParameters //支付签名参数
var orderInfo //订单号
function order(param,payment) {
    $('.loding').show()
    var packet = ''
    var ordered = [];
    if(no == '2'){
         packet = $.urlGet().id
    }else {
         packet = ''
    }
    var items = JSON.parse(params.items).items
    $.each(items, function (i, item) {
        if (item.num > 0) {
            ordered.push({
                "id": item.id,
                "num": item.num
            });
        }
    });
    // console.log(ordered)
    //去本地存储的用户信息
    // var params = JSON.parse(param.user);
    var openid = param.openid;
    var platform = param.platform;
    var redirect = JSON.parse(decodeURIComponent(param['redirect']));
    var id = redirect.id
    $('.loding').show()
    $.ajax({
        url: configApi('/order/create'),
        data: {
            access_token:redirect.token,
            openid: openid,
            platform: platform,
            items: JSON.stringify(ordered),
            id: id,
            coupon_id:packet,
            payment:payment
        },
        dataType: 'json',
        type: "POST",
        async:false,
        timeout: 8000 //超时时间设置，单位毫秒
    }).done(function (res) {
        console.log(res)
        $('.loding').hide()
        var data = res.data;
        if(res.success){
            if (data) {
                if (platform == 'dingTalk'){
                    window.location.href = data.aliPayUrl
                    return
                }
                if (payment === '1') {
                    // jsApiCall(data.wxPayParams, orderInfo);
                    console.log(data)
                    jsApiParameters = data.wxPayParams
                    orderInfo = data.order;
                    callpay();
                } else if (payment === '2'){
                    // console.log(data)
                    var tradeNO = data.alipay_trade_create_response.trade_no
                    orderInfo = data.order
                    // alert(data.alipay_trade_create_response)
                    tradePay(tradeNO)
                    // window.location.href = data.aliPayUrl;
                }else {
                    $('.loding').show()
                    orderInfo = data.order
                    behavior.track("成功支付",{
                        "platform":"余额",
                        "orderInfo":orderInfo.order_no
                    })
                    jump()
                }
            }else{
                layer.open({
                    content: res.message
                    ,skin: 'msg'
                    ,time: 2 //2秒后自动关闭
                });
            }
        }else {
            layer.open({
                content: res.message
                ,skin: 'msg'
                ,time: 2 //2秒后自动关闭
            });
        }
        // _payFlag = true;
    }).fail(function () {
        layer.open({
            content: "服务器异常,请退出重试"
            ,skin: 'msg'
            ,time: 2 //2秒后自动关闭
        });
    }).always(function (XMLHttpRequest, status) { //请求完成后最终执行参数
        if (status === 'timeout') {//超时,status还有success,error等值的情况
            // common.showDialog(0, 300, "网络请求超时,请重试!");
            setTimeout(function () {
                // common.showDialog(0, 300, "请稍候");
            }, 2000);
        }
    });
}
function jump() {
    // var redirect = JSON.parse(decodeURIComponent(param['redirect']));
    // $.ajax({
    //     url: configApi('/order/view'),
    //     data: {
    //         no:orderInfo.order_no,
    //         access_token:redirect.token,
    //         platform:params.platform
    //     },
    //     dataType: 'json',
    //     type: "get",
    // }).done(function (res) {
    //     if (res.success){
    //         console.log(res)
            // shareId = res.data.share.id
            window.location.href = './views/payResult.html' + '?&order_no=' + orderInfo.order_no + '';
    //     }else {
    //         layer.open({
    //             content: res.message
    //             ,skin: 'msg'
    //             ,time: 2 //2秒后自动关闭
    //         });
    //     }
    // }).fail(function () {
    //     "use strict"
    //     layer.open({
    //         content: "服务器异常,请退出重试"
    //         ,skin: 'msg'
    //         ,time: 2 //2秒后自动关闭
    //     });
    // })
}
function jsApiCall() {
    console.log(jsApiParameters)
    console.log(jsApiParameters, jsApiParameters.appId);
    if (jsApiParameters == 'undefined'){
        alert('签名未定义')
    }
    if(orderInfo == 'undefined'){
        alert('订单号为定义')
    }
    WeixinJSBridge.invoke(
        'getBrandWCPayRequest', {
            "appId": jsApiParameters.appId,     //公众号名称，由商户传入
            "timeStamp": jsApiParameters.timeStamp,         //时间戳，自1970年以来的秒数
            "nonceStr": jsApiParameters.nonceStr, //随机串
            "package": jsApiParameters.package,
            "signType": jsApiParameters.signType,         //微信签名方式：
            "paySign": jsApiParameters.paySign //微信签名
        },
        function (res) {
            // 支付测试环境还要将测试人员的微信号在公众号平台中加入测试支付白名单,不然调不起支付密码框
            // 返回信息get_brand_wcpay_request:ok
            //alert(res.errMsg)
            if (res.err_msg == "get_brand_wcpay_request:ok") {
                behavior.track("成功支付",{
                    "platform":"wechat",
                    "orderInfo":orderInfo.order_no
                })
                jump()
                // zhuge.track('成功支付', {
                //     '支付方式': 'wechat',
                //     '订单编号': orderInfo.order_no
                // }, function () {
                //     window.location.href = './views/payResult.html' + '?&order_no=' + orderInfo.order_no + '';
                // });
            } else {
                // _payFlag = true;
                behavior.track("取消支付",{
                    "platform":"wechat",
                    "orderInfo":orderInfo.order_no
                })
                // zhuge.track('取消支付', {
                //     '支付方式': 'wechat',
                //     '订单编号': orderInfo.order_no
                // }, function () {
                //     // window.location.href = './views/payResult.html' + '?result=1';
                // });
            }
        }
    )
}
function callpay() {
    if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
        } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', jsApiCall);
            document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
        }
    } else {
        jsApiCall();
    }
}
//阿里支付
function ready(callback) {
    if (window.AlipayJSBridge) {
        callback && callback();
    } else {
        document.addEventListener('AlipayJSBridgeReady', callback, false);
    }
}
function tradePay(tradeNO) {
    ready(function(){
        // 通过传入交易号唤起快捷调用方式(注意tradeNO大小写严格)
        AlipayJSBridge.call("tradePay", {
            tradeNO: tradeNO
        }, function (data) {
            // log(JSON.stringify(data));
            if ("9000" == data.resultCode) {
                jump()
            }
        });
    });
}

// pushHistory();
// window.addEventListener("popstate", function(e) {
//     window.location.href = './index.html'
//     params.removeItem('packet')
// }, false);
// function pushHistory() {
//     var state = {
//         title: "title",
//         url: "#"
//     };
//     window.history.pushState(state, "title", "#");
// }

